<?php
/**
 * 使用SVG绘制迷宫
 */
class MazeSVG
{
    /**
     * 输出迷宫
     * @var Maze $maze 迷宫
     */
    public function fetch($maze,$grid_size,$line_width)
    {
        $output="";
        $data=$maze->getWallStatusData();
        $line_style="stroke:rgb(0,0,0);stroke-width:".$line_width.";";
        $width=$grid_size * $maze->width;
        $height=$grid_size * $maze->height;
        $offset=$line_width/2;
        //输出迷宫边界
        $xs = $offset;
        $ys = $xs;
        $xe = $xs + $width;
        $ye = $ys + $height;
        $output.='<line x1="'.($xs+$grid_size-$offset).'" y1="'.$ys.'" x2="'.($xe+$offset).'" y2="'.$ys.'" style="'.$line_style.'"/>'."\r\n";
        $output.='<line x1="'.$xs.'" y1="'.$ye.'" x2="'.($xe-$grid_size+$offset).'" y2="'.$ye.'" style="'.$line_style.'"/>'."\r\n";
        $output.='<line x1="'.$xs.'" y1="'.($ys+$grid_size-$offset).'" x2="'.$xs.'" y2="'.($ye+$offset).'" style="'.$line_style.'"/>'."\r\n";
        $output.='<line x1="'.$xe.'" y1="'.$ys.'" x2="'.$xe.'" y2="'.($ye-$grid_size+$offset).'" style="'.$line_style.'"/>'."\r\n";
        //循环输出每个格子右侧和下方的墙
        foreach($data as $y => $line){
            foreach($line as $x => $item){
                $xs = $x * $grid_size;
                $ys = $y * $grid_size;
                $xe = $xs + $grid_size + $offset;
                $ye = $ys + $grid_size + $offset;
                if($item[0] === 0 && $x < $maze->width -1){
                    $output.='<line x1="'.$xe.'" y1="'.$ys.'" x2="'.$xe.'" y2="'.($ye+$offset).'" style="'.$line_style.'"/>'."\r\n";
                }
                if($item[1] === 0 && $y < $maze->height -1){
                    $output.='<line x1="'.$xs.'" y1="'.$ye.'" x2="'.$xe.'" y2="'.$ye.'" style="'.$line_style.'"/>'."\r\n";
                }
            }
        }
        $output='<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="'.($width+$line_width).'" height="'.($height+$line_width).'" version="1.1" xmlns="http://www.w3.org/2000/svg">'."\r\n".$output.'</svg>';
        return $output;
    }
}
